package p0;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Leetcode_8 {
    public int myAtoi(String str) {
        Matcher m = Pattern.compile("^[\\-+]?\\d+").matcher(str.trim());
        if (m.find()) {
            String num = m.group(0);
            boolean negative = num.charAt(0) == '-';
            int offset = 0;
            if (num.charAt(0) == '-' || num.charAt(0) == '+') {
                offset = 1;
            }
            int result = 0;
            int next;
            for (int i = num.length(); offset < i; result = next) {
                int digit = Character.digit(num.charAt(offset++), 10);
                if (result < -Integer.MIN_VALUE / 10) {
                    return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
                }
                next = result * 10 - digit;
                if (next > result) {
                    return Integer.MIN_VALUE;
                }
            }
            if (!negative) {
                result = -result;
                if (result < 0) {
                    return Integer.MAX_VALUE;
                }
            }
            return result;
        }
        return 0;
    }
}